//
//  CMNavigationBar.swift
//  CMKit
//
//  Created by travel on 2016/12/16.
//  Copyright © 2016年 covermedia. All rights reserved.
//

import UIKit


public enum CMNavigationItemViewType {
    case left, title, right
}

public class CMNavigationItemView: UIView {
    var type = CMNavigationItemViewType.title
    var itemView:UIView
    
    public init(view: UIView, type:CMNavigationItemViewType) {
        self.type = type
        itemView = view
        
        super.init(frame: view.bounds)
        addSubview(view)
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        itemView.frame = bounds
    }
}

public class CMNavigationBar: UINavigationBar {
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        
        var leftViews = [CMNavigationItemView]()
        var rightViews = [CMNavigationItemView]()
        for view in subviews {
            if let v = view as? CMNavigationItemView {
                switch v.type {
                case .left:
                    leftViews.append(v)
                case .title:
                    v.frame = CGRect(x: 0, y: v.frame.origin.y, width: frame.width, height: v.frame.height)
                case .right:
                    rightViews.append(v)
                }
            }
        }
        let compare:((CMNavigationItemView,CMNavigationItemView) -> Bool) = { (a:CMNavigationItemView, b:CMNavigationItemView) in
            return a.frame.maxX < b.frame.maxX
        }
        leftViews.sort(by: compare)
        rightViews.sort(by: compare)
        if let minX = leftViews.first?.frame.minX, minX > 0 {
            for v in rightViews {
                v.frame.origin.x = v.frame.origin.x - minX
            }
        }
        if let maxX = rightViews.last?.frame.maxX, maxX < frame.width {
            let offset = frame.width - maxX
            for v in rightViews {
                v.frame.origin.x = v.frame.origin.x + offset
            }
        }
    }
}
